#include <iostream>
#include <string>
#include <vector>
#include <semaphore.h>
static const int default_size = 5;
template <typename T>
class CycleQueue
{
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
public:
    CycleQueue(int max_size = default_size)
        : _cyclequeue(max_size)
        , _max_size(max_size)
        , _c_pos(0)
        , _p_pos(0)
    {
        sem_init(&_data_sem, 0, 0);
        sem_init(&_space_sem, 0, 5);
        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }
    void Push(const T& data)
    {
        P(_space_sem);
        pthread_mutex_lock(&_p_mutex);
        _cyclequeue[_p_pos++] = data;
        _p_pos %= _max_size;
        pthread_mutex_unlock(&_p_mutex);
        V(_data_sem);
    }
    void Pop( T* data)
    {
        P(_data_sem);
        pthread_mutex_lock(&_c_mutex);
        *data = _cyclequeue[_c_pos++];
        _c_pos %= _max_size;
        pthread_mutex_unlock(&_c_mutex);
        V(_space_sem);
    }
    ~CycleQueue() 
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    std::vector<T> _cyclequeue;
    int _max_size;
    int _c_pos;
    int _p_pos;
    sem_t _data_sem;
    sem_t _space_sem;
    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};